<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        document.body.innerHTML = "<div id=div1 >aaa</div>"+"<div id=div2 >bbb</div><div id=div3 >ccc</div>";
        for(var i = 1; i< 4; i++){
            document.getElementById('div'+ i).addEventListener('click',function(){
                alert(i); //all are 4!
            })
        }
    </script>
</body>
</html>